# -*- coding: utf-8 -*-
'''
Created on 2012-9-6


@author: Administrator
'''
from logic.login_session_mgr import LoginSessionMgr
import json
from core.db.reportx import *
from sqlalchemy.orm import class_mapper
from core.util.debug import Log
from webob import Request, Response
from service.server_config import SrvConfig
import uuid

def application(environ, start_response):
    '''
        entrance of apache wsgi application
    '''    
    req = Request(environ)
    res = Response()
    
    ReportService.process(req, res)
    
    return res(environ, start_response)

class ReportService(object):
    '''
        company report application      
    '''
    __setup__ = False
    log = None   
    
    
    @staticmethod
    def process(req, res):
        if ReportService.__setup__ == False:
            Log.setPath(SrvConfig.getLogPath())
            ReportService.log = Log()            
            ReportService.__setup__ = True        
            
        try:
            #检查 TOKEN 的有效性 
            dbsession = SrvConfig.getDefaultDBSession()
            company_id = req.params["company_id"]
            username = req.params["username"]
            token = req.params["token"]
            if LoginSessionMgr.isSessionValid(company_id, username, token, dbsession) is False:
                res.json = {'ret':107, 'msg':'token invalid'}                    
                            
            reportService = ReportService(dbsession)
            reportService.getCompanyReport(req, res)
                        
        except Exception,e:
            ReportService.log.e('ReportService:process, exception %s' % e)
            res.json = {'ret':-1, 'msg':'exception'}
        finally:
            dbsession.close()    
               

    def __init__(self, dbsession):
        self.dbsession = dbsession
    
    
    def getCompanyReport(self, req, res):
        '''
            公司X库保存的统计报表      
        '''   
        config_table = req.params['type']
        
        ReportService.log.d("ReportService:getCompanyReport, tablename:%s" % config_table)
        config_table_classes = {}         
        config_table_classes["dish_report"] =dish_report.Dish_report
        config_table_classes["payment_report"] = payment_report.Payment_report 
        config_table_classes["sell_analysis"] = sell_analysis.Sell_analysis 
        config_table_classes["stat_class_report"] =stat_class_report.Stat_class_report 

        config_orderby = {}
        config_orderby["dish_report"] ="stat_class_name asc,dish_name asc,sold_count asc "
        config_orderby["payment_report"] = "sale_count asc "
        config_orderby["sell_analysis"] = "uuid asc "
        config_orderby["stat_class_report"] = "sort_rank asc  "
        
        config_prolist={}
        config_prolist["dish_report"] ="pro_salesrank"
        config_prolist["payment_report"] = "pro_paymentmode"
        config_prolist["sell_analysis"] = "pro_sellanalysis"
        config_prolist["stat_class_report"] = "pro_statclass"
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            orderby=config_orderby[config_table]
            proname=config_prolist[config_table]
            self._getCompanyReportByTable(req, res, table_class, orderby, config_table, proname)
        else:
            ReportService.log.e('ReportService:getCompanyReport, unknown configure')
            res.json = {'ret':-1, 'msg':'unknown configure'}
                    

    def _getCompanyReportByTable(self, req, res, table_class, orderby, config_table, proname):
        '''
            对读配置的响应
            table_class 要操作的表对应的ORM类
        '''
        try:                       
            company_id = req.params['company_id']  
            start_time = req.params['start_time']
            end_time = req.params['end_time']
            
            table_class.doMapping(company_id)            

            #首先清理10分钟以前的报表记录
            self.dbsession.execute("set SQL_SAFE_UPDATES=0")
            self.dbsession.execute("delete from  report_%s.%s  where  TIMESTAMPDIFF(minute,modify_time,now())>=10 " % (company_id,config_table))            
            self.dbsession.commit()
            tempuuid = uuid.uuid4()            
            
            #设置参数
            tempsql_qz = "set @b_t='%s'; set @e_t='%s' ;  " % (start_time,end_time)
            tempsql_qz =tempsql_qz+" set @uid='%s' ;" % tempuuid
            shopidlist = req.params['shopidlist']
            shopidlist = shopidlist[1:-1].split(',')
            ReportService.log.d('ReportService:_getCompanyReportByTable, shopidlist:%s' % shopidlist)
            for element in shopidlist:
                tempsql = "use shop_order_%s_%s  ;" % (company_id,element)
                tempsql = tempsql+tempsql_qz;
                tempsql = tempsql+"  call %s(@b_t,@e_t,@uid) ; " % proname
                self.dbsession.execute(tempsql) 
                ReportService.log.e('sqlstr:%s' % tempsql)
                
                self.dbsession.commit()
                        
            tempfiltername = "uuid='%s'" % tempuuid;          
            #获取记录操作
            query_result = self.dbsession.query(table_class).filter(tempfiltername).order_by(orderby).all()            
            table_fields = {}                       
            for col in (class_mapper(table_class).mapped_table.c):
                table_fields[col.name] = col.name
                                                                                           

            ReportService.log.d('ReportService:_getCompanyReportByTable :%s' % repr(table_fields))
                
            returnlist = []                
            dicmy = {}
            dicmy["ret"] = 0
            dicmy["msg"] = 'success'
            icount = 0                     
            #如果是sell_analysis 就把列分装成表的形式                             
            if config_table == "sell_analysis":
                for r in query_result:
                    icount=1
                    dicmyFF={}
                    dicmyFF["sellname"]="订单总数"
                    dicmyFF["sellvalue"]=r.order_count
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="订单总金额"
                    dicmyFF["sellvalue"]=r.order_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="总消费人数"
                    dicmyFF["sellvalue"]=r.total_customer
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="最大消费金额"
                    dicmyFF["sellvalue"]=r.max_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="最小消费金额"
                    dicmyFF["sellvalue"]=r.min_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="赠送总金额"
                    dicmyFF["sellvalue"]=r.free_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="折扣总金额"
                    dicmyFF["sellvalue"]=r.discount_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="服务费"
                    dicmyFF["sellvalue"]=r.service_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="抹零金额"
                    dicmyFF["sellvalue"]=r.zero_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    
                dicmy['data'] = returnlist
                res.json = dicmy                            
            else:
                res.json = {'ret':-1, 'msg':'unspported report'}
                ReportService.log.e('ReportService:_getCompanyReportByTable, unspported report')
        except Exception, e:           
            ReportService.log.e('ReportService:_getCompanyReportByTable exception:%s' % e)
            res.json = {'ret':-1, 'msg':'exception'}
        

        
